<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2022/7/23
 * Time: 14:35
 */

namespace app\backstage\controller;


use app\backstage\classes\helper\JwtToken;
use app\backstage\logic\ManagerUserLogic;
use app\backstage\model\ManagerRole;
use app\backstage\model\QuickAppToManagerAccess;
use think\captcha\Captcha;
use think\Controller;
use think\Db;
use think\facade\Cookie;
use think\facade\Request;

class ManagerUser extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => ['login', 'verify']],
        'VerifyPower' => ['except' => ['login', 'verify', 'password', 'logout', 'sonUsers']],
    ];

    private function checkAuth($ManagerUser,$params,$msg)
    {
        $rolename = 'other';
        $source_id = cookie('source_id');
        if($source_id)
        {
            $role_id = Db::table('cms_manager_user')->where('id',$source_id)->value('role_id');
            $rolename = Db::table('cms_manager_role')->where('id',$role_id)->value('alias');
        }

        if(request()->_role->alias == 'eb' && $rolename != 'admin')
        {
            $agents = $ManagerUser->getAgents(request()->_user->id);
            if(empty($agents))
            {
                return ['code'=>102,'msg'=>$msg];
            }

            if(!in_array($params['id'],array_column($agents,'id')))
            {
                return ['code'=>102,'msg'=>$msg];
            }

        }

        if(request()->_role->alias == 'agent' && $rolename != 'admin')
        {
            $channels = Db::table('cms_manager_user')->where('parent_id','=',request()->_user->id)
                ->field('id,account')->select();
            
            if(empty($channels))
            {
                return ['code'=>102,'msg'=>$msg];
            }

            if(!in_array($params['id'],array_column($channels,'id')))
            {
                return ['code'=>102,'msg'=>$msg];
            }
        }

        return ['code'=>100,'msg'=>'校验通过'];
    }

    /*账户禁用*/
    public function disable()
    {
        $ManagerUser = \think\facade\App::model('Account','logic');

        if( Request::isGet() ){

            $params = Request::get('','','strip_tags');
            $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.del');
            if (true !== $result) {
                $this->error($result);
            }

            $info = $ManagerUser->getInfo($params['id']);

            if(strlen($info['account']) < 1){
                $this->error('该记录不存在');
            }

            $this->assign('info',$info);
            return $this->fetch();
        }

        $params = Request::post('','','strip_tags,trim');
        $verify_result = $this->validate($params, 'app\backstage\validate\ManagerValidate.del');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $checkResult = $this->checkAuth($ManagerUser,$params,'该账户无法操作');
        if($checkResult['code'] != 100)
        {
            return json($checkResult);
        }

        $where[]         = ['id','=',$params['id']];
        $data['status']  = $params['status'];

        $ManagerUserLogic = new \app\backstage\logic\ManagerUserLogic();
        $result         = $ManagerUserLogic->editInfo($where,$data);

        return json($result);


    }

    /*重置密码*/
    public function reset_pwd()
    {
        $ManagerUser = \think\facade\App::model('Account','logic');

        if( Request::isGet() ){

            $params = Request::get('','','strip_tags');
            $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.del');
            if (true !== $result) {
                $this->error($result);
            }

            $info = $ManagerUser->getInfo($params['id']);

            if(strlen($info['account']) < 1){
                $this->error('该记录不存在');
            }

            $this->assign('info',$info);
            return $this->fetch();
        }

        $params = Request::post('','','strip_tags,trim');
        $verify_result = $this->validate($params, 'app\backstage\validate\ManagerValidate.reset_pwd');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        $checkResult = $this->checkAuth($ManagerUser,$params,'该账户无法重置密码');
        if($checkResult['code'] != 100)
        {
            return json($checkResult);
        }

        $data['id']         = $params['id'];
        $data['password']   = $params['password'];

        $ManagerUserLogic = new \app\backstage\logic\ManagerUserLogic();
        $result         = $ManagerUserLogic->editPwd($data);

        return json($result);
    }

    /*来源账户切回*/
    public function switch_account_source()
    {
        $source_id = cookie('source_id');
        $source_id_second = cookie('source_id_second');
        $source_id_third = cookie('source_id_third');

        if(request()->_role->alias == 'eb')
        {
            $token = JwtToken::createToken($source_id);
            cookie('source_id',null);

        }else if(request()->_role->alias == 'agent')
        {
            if($source_id_second)
            {
                $token = JwtToken::createToken($source_id_second);
                cookie('source_id_second',null);
            }else{
                $token = JwtToken::createToken($source_id);
                cookie('source_id',null);
            }

        }else if(request()->_role->alias == 'channel')
        {
            if($source_id_third)
            {
                $token = JwtToken::createToken($source_id_third);
                cookie('source_id_third',null);
            }else{
                $token = JwtToken::createToken($source_id);
                cookie('source_id',null);
            }

        }else{
            $token = JwtToken::createToken($source_id);
            cookie('source_id',null);
        }

        Cookie::set('access_token', $token, 3600 * 24 * 30);

        return json(['code'=>100,'msg'=>'账号切换成功']);
    }

    /*下属账户切换*/
    public function switch_account()
    {
        $params = Request::param('', '', 'strip_tags');
        $ManagerUser = \think\facade\App::model('Account', 'logic');
        $source_id = cookie('source_id');
        $rolename = 'other';
        if($source_id)
        {
            $role_id = Db::table('cms_manager_user')->where('id',$source_id)->value('role_id');
            $rolename = Db::table('cms_manager_role')->where('id',$role_id)->value('alias');
        }

        if(request()->_role->alias == 'eb' && $rolename != 'admin')
        {
            $agents = $ManagerUser->getAgents(request()->_user->id);
            if(empty($agents))
            {
                return json(['code'=>102,'msg'=>'该代理无法切换账户']);
            }

            if(!in_array($params['id'],array_column($agents,'id')))
            {
                return json(['code'=>102,'msg'=>'该代理无法切换账户']);
            }

        }

        if(request()->_role->alias == 'agent' && $rolename != 'admin')
        {
            $channels = Db::table('cms_manager_user')->where('parent_id','=',request()->_user->id)
                ->field('id,account')->select();

            if(empty($channels))
            {
                return json(['code'=>102,'msg'=>'该投放号无法切换账户']);
            }

            if(!in_array($params['id'],array_column($channels,'id')))
            {
                return json(['code'=>102,'msg'=>'该投放号无法切换账户']);
            }
        }

        if(request()->_role->alias == 'eb')
        {
            Cookie::set('source_id_second', request()->_user->id, 3600 * 24 * 30);
        }else if(request()->_role->alias == 'agent')
        {
            Cookie::set('source_id_third', request()->_user->id, 3600 * 24 * 30);
        }else{
            Cookie::set('source_id', request()->_user->id, 3600 * 24 * 30);
        }

        $token = JwtToken::createToken($params['id']);
        Cookie::set('access_token', $token, 3600 * 24 * 30);

        return json(['code'=>100,'msg'=>'账号切换成功']);
    }

    /**
     * 登录页
     * @return mixed
     * @Author: whh
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.login');
            if (true !== $result) {
                $this->error($result);
            }
            $ManagerUserLogic = new \app\backstage\logic\ManagerUserLogic();
            $res = $ManagerUserLogic->sign_in($params);
            return $res;
        }
        return $this->fetch();
    }

    /**
     * 退出
     * @Author: whh
     */
    public function logout()
    {
        Cookie::set('access_token', null);
        Cookie::set('quick_id', null);
        cookie('source_id',null);
        cookie('source_id_second',null);
        cookie('source_id_third',null);
        $this->success();
    }

    /**
     * 验证码
     * @return \think\Response
     * @Author: whh
     */
    public function verify()
    {
        $config = [
            // 验证码字体大小
            'fontSize' => 30,
            // 验证码位数
            'length' => 4,
            // 验证码杂点
            'useNoise' => true,
            // 是否画混淆曲线
            'useCurve' => false,
            //纯数字
            'codeSet' => '0123456789',
        ];
        $captcha = new Captcha($config);
        $captcha->fontttf = '5.ttf';
        return $captcha->entry();
    }


    /**
     * 密码页
     * @return mixed|\think\response\Json
     * @Author: whh
     */
    public function password()
    {
        if ($this->request->post()) {
            $params = $this->request->post();
            $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.password');
            if (true !== $result) {
                $this->error($result);
            }
            $logic = new ManagerUserLogic();
            return $logic->resetPassword(request()->_user, $params['oldPassword'], $params['password']);
        }
        return $this->fetch();
    }

    /**
     * 后台用户
     * @return mixed
     */
    public function user()
    {
        //查询角色
        $roles = ManagerRole::getList();
        $qas = \app\common\model\QuickApp::field("id,name")->all();
        $this->assign('roles', $roles);
        $this->assign('qas', $qas);
        return $this->fetch();
    }

    /**
     * 后台用户列表接口
     * @return \think\response\Json
     */
    public function userList()
    {
        $id = input('id');
        $account = input('account');
        $role_id = input('role_id');
        $quick_id = input('quick_id');
        $page = input('page', 1);
        $limit = input('limit', 10);
        $where = [];
        if ($id != '') {
            $where[] = ['id', '=', $id];
        }
        if ($account != '') {
            $where[] = ['account', 'like', "%$account%"];
        }
        if ($role_id != '') {
            $where[] = ['role_id', '=', $role_id];
        }
        if ($quick_id != '') {
            $uIds = QuickAppToManagerAccess::where('quick_id', $quick_id)->column('uid');
            $where[] = ['id', 'in', $uIds];
        }
        $field = "id,account,role_id,parent_id,status,last_login_time,last_login_ip,remarks,create_time,sharing_ratio,channel_code,scale";
        $list = \app\backstage\model\ManagerUser::getList($where, $field, 'id desc', $page, $limit, ['role', 'parent']);
        foreach ($list as $k => $v) {
            if($v->role_id != 9 && $v->role_id != 5)
            {
                $list[$k]['scale'] = '';
            }
            $list[$k]['app_count'] = count($v->apps);
            $list[$k]['app_count_disable'] = Db::table('quick_app_mp_manager_disable')->where('uid',$v['id'])->count('id');
        }
        $count = \app\backstage\model\ManagerUser::getCount($where);
        return sucJson($list, $count);
    }

    /*单元格编辑分成比例*/
    public function editSharing_ratio()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.editsharing_ratio');
        if (true !== $result) {
            $this->error($result);
        }

        $role_id = Db::table('cms_manager_user')->where('id',$params['id'])->value('role_id');
        $alias = Db::table('cms_manager_role')->where('id',$role_id)->value('alias');

        if($alias != 'channel'  && $alias != 'agent')
        {
            $this->error('该角色不用设置分成比例');
        }

        $manager = \app\backstage\model\ManagerUser::get($params['id']);
        $manager->sharing_ratio = $params['sharing_ratio'];
        $manager->save();
        $this->success();
    }

    /**
     * 单元格编辑备注
     */
    public function editRemarks()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.editRemarks');
        if (true !== $result) {
            $this->error($result);
        }
        $manager = \app\backstage\model\ManagerUser::get($params['id']);
        $manager->remarks = $params['remarks'];
        $manager->save();
        $this->success();
    }

    /**
     * 用户表单页
     * @return mixed|string
     */
    public function managerForm()
    {
        $id = input('id', 0);
        $manager = null;
        if ($id != 0) {
            $manager = \app\backstage\model\ManagerUser::get($id);
            if (!$manager) {
                return '用户不存在';
            }
        }
        $this->assign('manager', $manager);
        $roles = ManagerRole::getList();
        $this->assign('roles', $roles);
        /**
         * 查询商务
         */
        $ebRole = ManagerRole::getRoleByAlias('eb');
        $ebs = \app\backstage\model\ManagerUser::where('role_id', $ebRole['id'])->select();
        /**
         * 查询代理
         */
        $agentRole = ManagerRole::getRoleByAlias('agent');
        $agents = \app\backstage\model\ManagerUser::where('role_id', $agentRole['id'])->select();
        $this->assign('ebs', $ebs);
        $this->assign('agents', $agents);
        return $this->fetch();
    }

    /**
     * 格式化穿梭框所需数据
     * @param $data
     * @param int $isHave
     * @return array
     */
    private function empowerDataToJson($data, $isHave = 0)
    {
        $formatData = [];
        foreach ($data as $k => $v) {
            if ($isHave) {
                $formatData[] = $v['id'];
            } else {
                $formatData[$k]['value'] = $v['id'];
                $formatData[$k]['title'] = $v['name'];
            }
        }
        return $formatData;
    }


    /**
     * 授权页面
     * @return mixed|string
     */
    public function empowerForm()
    {
        $id = input('id');
        $manager = null;
        $manager = \app\backstage\model\ManagerUser::get($id);
        if (!$manager) {
            return '用户不存在';
        }
        if ($manager->role->alias != 'channel' && $manager->role->alias != 'agent' && $manager->role->alias != 'eb') {
            return '该角色无需授权App';
        }
        $msg = '';
        if ($manager->role->alias == 'channel'){
            $msg = '投放号只能授权一个App';
        }
        $this->assign('msg',$msg);
        $role = request()->_role;
        $user = request()->_user;
        if ($role->alias == 'agent' || $role->alias == 'eb') {
            $allQas = $user->apps;
        } else {
            $allQas = \app\common\model\QuickApp::getList();
        }
        $haveQas = $manager->apps;
        $allQas = $this->empowerDataToJson($allQas);
        $haveQas = $this->empowerDataToJson($haveQas, 1);
        foreach ($allQas as $k => $v) {
            if (in_array($v['value'], $haveQas)) {
                $allQas[$k]['disabled'] = true;
            }
        }
        $this->assign('manager', $manager);
        $this->assign('allQas', json_encode($allQas));
        $this->assign('haveQas', json_encode($haveQas));
        return $this->fetch();
    }

    /**
     * 授权App
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function managerEmpowerApp()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.managerEmpowerApp');
        if (true !== $result) {
            $this->error($result);
        }
        $manager = \app\backstage\model\ManagerUser::get($params['id']);
        if (!$manager) {
            $this->error('用户不存在');
        }
        $role = request()->_role;
        if ($manager->role->alias == 'channel' && $role->alias != 'agent') {
            $this->error('授权App到投放号，请使用上级代理账号后台授权');
        }
        $quick_ids = input('quick_ids', '');
        $logic = new ManagerUserLogic();
        $result = $logic->managerEmpowerApp($manager, $quick_ids);
        return $result;
    }

    /*
     * 禁用授权App
     * */
    public function empowerFormDisable()
    {
        $id = input('id');
        $manager = null;
        $manager = \app\backstage\model\ManagerUser::get($id);
        if (!$manager) {
            return '用户不存在';
        }

        $msg = '';

        $this->assign('msg',$msg);
        $role = request()->_role;
        $user = request()->_user;

        $allQas_q = Db::table('quick_app_mp_manager')->where('uid',$id)->field('quick_id')->select();
        $quick_id_gh = array_column($allQas_q,'quick_id');
        $quicks = Db::table('quick_app')->where('id','in',$quick_id_gh)->column('id,name');
        $allQas = [];
        foreach ($allQas_q as $k=>$v)
        {
            $allQas[$k]['title'] = isset($quicks[$v['quick_id']]) ? $quicks[$v['quick_id']] : '';
            $allQas[$k]['value'] = $v['quick_id'];
        }

        $haveQas = Db::table('quick_app_mp_manager_disable')->where('uid',$id)->column('quick_id');

        $this->assign('manager', $manager);
        $this->assign('allQas', json_encode($allQas));
        $this->assign('haveQas', json_encode($haveQas));
        return $this->fetch();
    }

    /**
     * 禁用授权App
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function managerEmpowerAppDisable()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.managerEmpowerApp');
        if (true !== $result) {
            $this->error($result);
        }
        $manager = \app\backstage\model\ManagerUser::get($params['id']);
        if (!$manager) {
            $this->error('用户不存在');
        }
        $role = request()->_role;

        $quick_ids = input('quick_ids', '');
        $quick_ids = array_unique(explode(',', $quick_ids));
        $quick_ids = array_unique($quick_ids);

        foreach ($quick_ids as $v)
        {
            $record = Db::table('quick_app_mp_manager_disable')->where('uid',$params['id'])
                    ->where('quick_id',$v)->field('id')->findOrEmpty();
            if(empty($record))
            {
                Db::table('quick_app_mp_manager_disable')->insert(['uid'=>$params['id'],'quick_id'=>$v]);
            }
        }

        if($quick_ids)
        {
            Db::table('quick_app_mp_manager_disable')->where('uid',$params['id'])
                ->where('quick_id','not in',$quick_ids)->delete();
        }

        return json(['code' => 1, 'msg' => 'ok', 'count' => 0, 'data' => []]);
    }

    /**
     * 添加后台用户
     * @throws \think\Exception
     * @Author: whh
     */
    public function addUser()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.addUser');
        if (true !== $result) {
            $this->error($result);
        }
        $role = ManagerRole::get($params['role_id']);
        if (!$role) {
            $this->error('角色不存在');
        }

        $params['sharing_ratio'] = 0;
        if ($role->alias == 'channel' || $role->alias == 'agent') {
            $params['sharing_ratio'] = 90;
            if ($role->alias == 'channel' && (!isset($params['agent_id']) || !$params['agent_id'])) {
                $this->error('添加投放号必须选择上级代理');
            }
            if ($role->alias == 'channel'){
                $params['sharing_ratio'] = Db::table('cms_manager_user')->where(['id' => $params['agent_id']])->value('sharing_ratio') ?? 0;;
            }
        }
        $logic = new ManagerUserLogic();
        $res = $logic->setUser($params);
        if ($res['code'] === 0){
            return errJson($res['msg']);
        }
        $this->success();
    }


    /**
     * 修改后台用户
     * @throws \think\Exception
     * @Author: whh
     */
    public function editUser()
    {
        $params = $this->request->param();
        if (!isset($params['status'])) {
            $params['status'] = 0;
        }
        $result = $this->validate($params, 'app\backstage\validate\ManagerValidate.editUser');
        if (true !== $result) {
            $this->error($result);
        }
        $logic = new ManagerUserLogic();
        $logic->setUser($params, $params['id']);
        $this->success();
    }


    /**
     * 下属用户
     * @return \think\response\Json
     */
    public function sonUsers()
    {
        $key = input('key');
        $page = input('page', 1);
        $alias = input('alias');
        $limit = 10;
        $where = [];
        if ($alias != '') {
            $findRole = ManagerRole::getRoleByAlias($alias);
            if ($findRole) {
                $where[] = ['role_id', '=', $findRole['id']];
            }
        }
        $role = request()->_role;
        $user = request()->_user;
        if ($role->alias == 'agent' || $role->alias == 'channel' || $role->alias == 'eb') {
            if ($role->alias == 'eb' && $alias == 'channel') {
                $uModel = new \app\backstage\model\ManagerUser();
                $agentIds = $uModel->sonUsersIds($user->id);
                $where[] = ['parent_id', 'in', $agentIds];
            } else {
                $where[] = ['parent_id', '=', $user->id];
            }
        }
        $query = new \app\backstage\model\ManagerUser();
        $query = $query->field("id value,account name")->where($where);
        if ($key != '') {
            $query = $query->where(function ($query) use ($key) {
                $query->where('id', $key)
                    ->whereOr('account', 'like', "%$key%");
            });
        }
        $count = $query->count();
        $data = $query->order("id desc")->page($page, $limit)->select();
        return sucJson($data, intval($count));
    }

}